package top.codef.secure.config.delegates;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import com.fasterxml.jackson.databind.ObjectMapper;

import top.codef.secure.config.interfaces.CerberusHttpSecurityConfig;
import top.codef.secure.handlers.CerberusAccessDeniedHandler;
import top.codef.secure.handlers.CerberusExceptionTranslateHandler;
import top.codef.secure.properties.CerberusExceptionProperties;

@Configuration
@Order(3)
@EnableConfigurationProperties(CerberusExceptionProperties.class)
@ConditionalOnProperty(name = "cerberus.secure.exception.enabled", havingValue = "true", matchIfMissing = true)
public class CerberusExceptionConfig implements CerberusHttpSecurityConfig {

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private CerberusExceptionProperties cerberusExceptionProperties;

	private final Log logger = LogFactory.getLog(CerberusExceptionConfig.class);

	@Override
	public void secure(HttpSecurity httpSecurity) throws Exception {
		logger.debug("异常处理设置");
		httpSecurity.exceptionHandling(
				x -> x.accessDeniedHandler(new CerberusAccessDeniedHandler(objectMapper, cerberusExceptionProperties))
						.authenticationEntryPoint(new CerberusExceptionTranslateHandler(objectMapper)));
	}

}
